<?php

namespace app\common\func;

use app\admin\model\AuthGroupAccess;
use app\api\controller\Cloudcomputing;
use app\api\controller\Remittance;
use app\api\controller\Wx;
use app\common\model\GiftOrder;
use app\common\model\ProductApply;
use fast\Tree;
use think\Db;

class Tools
{

    public static function sendGift($sn){
        $order = GiftOrder::where(['sn' => $sn,'status' => 1])->find();
        $flowMoney = Db::name("terminal")->alias("t")
            ->join("product p","t.product_id = p.id","left")
            ->where(['t.sn' => $sn])
            ->column("p.flow");
        if($order){
            if (in_array($order->type, [1, 2])) {
                $pay = Tools::pay($sn, $order->user_id, $flowMoney);
                if ($pay['code'] == 0) {
                    \exception($pay['msg']);
                }

                $order->status = 2;
                $order->save();
            } elseif ($order->type == 3) {
                $order->status = 2;
                $order->save();
            }
        }
    }

    public static function checkRole($groupId){
        if($groupId == Constant::$masterGroup){
            return 4;
        }
        $group = Lib::getGroup($groupId);
        if($group->pid == Constant::$masterGroup){
            return 3;
        }
        if($group->pid == Constant::$masterKefu){
            return 5;
        }
        return 0;
    }

    public static function getAdminGroupId($adminId){
        return AuthGroupAccess::where(['uid' => $adminId])->column('group_id');
    }

    /**
     * @param $mainId
     * @param int $type || 0=默认，1=所有下级(树形)，2=直属下级（二维数组），3=所有下级（二维数组），4=所有下级ID（数组）
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getGroupTree($mainId, $type = 0)
    {
        $list = Db::name("auth_group")->where(["status" => 'normal'])->field("id,pid,name,content")->select();
        $query = Tree::instance()->init($list, 'pid');
        switch ($type) {
            case 1:
                $data = $query->getTreeArray($mainId);
                break;
            case 2:
                $data = $query->getChild($mainId);
                break;
            case 3:
                $data = $query->getChildren($mainId);
                break;
            case 4:
                $data = $query->getChildrenIds($mainId);
                break;
            default:
                $data = [];
        }
        return $data;
    }

    public static function pay($sn,$userId,$flow){
        $orderFinish = \app\common\model\Remittance::where(['sn' => $sn,"payment_status" => 2])->find();
        if($orderFinish){
            return ["code" => 0, "msg" => "该设备已提现"];
        }
        $order = Remittance::createOrder($sn,$userId,$flow);
        if($order['code'] == 0){
            return ["code" => 0, "msg" => $order['msg']];
        }
        $orderNum = $order['order_num'];

        $result = Cloudcomputing::singleWithdrawal($orderNum);
        if($result['code'] != 200){
            return ["code" => 0, "msg" => $result['msg']];
        }

        return ["code" => 1];
    }

    public static function saveOrder($userId,$giftId,$sn,$province,$city,$district,$address){
        $giftOrder = GiftOrder::where(['status' => 1,'sn' => $sn])->find();
        if(!$giftOrder){
            $order = new GiftOrder();
            $order->user_id = $userId;
            $order->gift_id = $giftId;
            $order->sn = $sn;
            $order->province = $province;
            $order->city = $city;
            $order->district = $district;
            $order->address = $address;
            $order->save();
            return $order;
        }else{
            return false;
        }
    }

    public static function operateApply($sn,$userId){
        $apply = Lib::getApplyBySn($userId,$sn);
        if($apply){
            $apply->status = 3;
            $apply->save();
        }
    }

    public static function importExcel($pathUrl)
    {
        $path = ROOT_PATH . "public" . $pathUrl;
        $spreadSheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($path);
        $data = $spreadSheet->getActiveSheet()->toArray(null, true, true, false);
        $list = [];
        if(count($data) > 0){
            for ($i = 0;$i<count($data);$i++){
                if($data[$i][0] != null){
                    $list[$i][0] = $data[$i][0];
                }
            }
        }
        return $list;
    }

    public static function saveProductApply($productId,$type,$userId,$addressId){
        $apply = new ProductApply();
        $apply->product_id = $productId;
        $apply->type = $type;
        $apply->user_id = $userId;
        $apply->number = 1;
        if($addressId > 0){
            $address = Lib::getUserAddressById($addressId);
            $apply->name = $address->name;
            $apply->phone = $address->mobile;
            $apply->address = $address->province.$address->city.$address->district.$address->address;
        }
        $result = $apply->save();

        self::sendSaleMessage();

        return $result == false ? false : $apply->id;
    }

    public static function sendSaleMessage(){
        $user = Lib::getSaleUserList();
        if(count($user) > 0){
            foreach ($user as $key => $val){
                self::sendScore($val->id,$val->nickname,"有新的设备申请",0,"请尽快处理");
            }
        }
    }

    //--------------------------------------------消息模板----------------------------------------------

    public static function sendTran($userId,$rate,$productName,$tranAmount,$arriveAmount,$tradingTime,$sn){
        $user = Lib::getUserById($userId);
        $openid = $user->wx_open_id;
//        $url = "http://community.fdkj.top/pages/public/trading?sn=".$sn;
        $url = "http://community.fdkj.top/pages/version5/index/customer/index";
        $data = array(
            'thing4' => array('value' => $rate . "-" . $productName, 'color' => ''),
            'amount6' => array('value' => $tranAmount, 'color' => ''),
            'amount1' => array('value' => $arriveAmount, 'color' => ''),
            'time3' => array('value' => $tradingTime, 'color' => '')
        );

        $wx = new Wx();
        $wx->send_template_message($openid,1,$data,$url);
    }

    public static function sendOrder($userId,$productName,$name,$mobile,$orderTime,$kefu){
        $user = Lib::getUserById($userId);
        $openid = $user->wx_open_id;
        $url = "http://community.fdkj.top/pages/public/orderConfirm?id=1";
        $data = array(
            'thing19' => array('value' => $productName, 'color' => ''),
            'thing17' => array('value' => $name, 'color' => ''),
            'thing18' => array('value' => $mobile, 'color' => ''),
            'time6' => array('value' => $orderTime, 'color' => ''),
            'phone_number5' => array('value' => $kefu, 'color' => '')
        );

        $wx = new Wx();
        $wx->send_template_message($openid,2,$data,$url);
    }

    public static function sendFlow($userId,$flowId,$productName,$flowMoney,$time){
        $user = Lib::getUserById($userId);
        $openid = $user->wx_open_id;
        $url = "http://community.fdkj.top/pages/public/flowreturn?id=".$flowId;
        $data = array(
            'thing8' => array('value' => $productName."-流量费", 'color' => ''),
            'amount10' => array('value' => $flowMoney, 'color' => ''),
            'time3' => array('value' => $time, 'color' => '')
        );

        $wx = new Wx();
        $wx->send_template_message($openid,3,$data,$url);
    }

    public static function sendFinishDelivery($userId){
        $user = Lib::getUserById($userId);
        $openid = $user->wx_open_id;
        $url = "http://community.fdkj.top/pages/public/receiveGoods?id=1";
        $data = array(
            'thing9' => array('value' => "盛付通-流量费", 'color' => ''),
            'thing19' => array('value' => "盛付通-流量费", 'color' => ''),
            'thing3' => array('value' => "盛付通-流量费", 'color' => ''),
            'time4' => array('value' => "", 'color' => ''),
            'thing15' => array('value' => "", 'color' => '')
        );

        $wx = new Wx();
        $wx->send_template_message($openid,4,$data,$url);
    }

    public static function sendBind($userId,$time){
        $user = Lib::getUserById($userId);
        $openid = $user->wx_open_id;
        $url = "http://community.fdkj.top/pages/version5/index/customer/index";
        $data = array(
            'character_string1' => array('value' => $user->mobile, 'color' => ''),
            'character_string4' => array('value' => $user->mobile, 'color' => ''),
            'character_string2' => array('value' => Lib::getUserCountTerminal($userId), 'color' => ''),
            'time3' => array('value' => $time, 'color' => ''),
            'thing5' => array('value' => "风动社区", 'color' => '')
        );

        $wx = new Wx();
        $wx->send_template_message($openid,5,$data,$url);
    }

    public static function sendScore($userId,$name,$question,$serviceId,$evaluate = "已处理，待评价！"){
        $user = Lib::getUserById($userId);
        $openid = $user->wx_open_id;

        $url = $serviceId > 0 ? "http://community.fdkj.top/pages/public/evaluate?id=".$serviceId : "";
        $data = array(
            'thing7' => array('value' => $name, 'color' => ''),
            'thing1' => array('value' => $question, 'color' => ''),
            'thing5' => array('value' => $evaluate, 'color' => '')
        );

        $wx = new Wx();
        $wx->send_template_message($openid,6,$data,$url);
    }

    //--------------------------------------------消息模板----------------------------------------------
}
